//
//  LFOrderTableViewController.m
//  LoveFruit
//
//  Created by Hannibal_zj on 16/9/23.
//  Copyright © 2016年 张令林. All rights reserved.
//

#import "LFOrderTableViewController.h"
#import "LFTopTableViewCell.h"
#import "LFBottomOneCell.h"
#import "LFBottomTwoCell.h"
#import "LFBottomThreeCell.h"
#import "LFGoodsCell.h"
#import "LFHotSellerModel.h"
#import "LFcertainView.h"
#import "LFShopCarPayViewController.h"
#import "LFHomeViewController.h"
#import "LFRemarkViewController.h"
#import "LFFreshOrdergoodsModel.h"
#import "KPTimePicker.h"
#import "Categories.h"

static int num = 0;
@interface LFOrderTableViewController ()<UIActionSheetDelegate,LFcertainViewDelegate,KPTimePickerDelegate>
// 总金额
@property (nonatomic,assign)NSInteger money;

@property (nonatomic,assign)NSInteger addmoney;

@property (nonatomic,weak) LFcertainView *certainView;

@property (nonatomic, strong) UIView *bgView;

@property (nonatomic, weak) LFcertainView *bgFootView;

@property (nonatomic, strong) NSMutableArray * freshOrderArray;
//时间
@property (strong,nonatomic) KPTimePicker *timePicker;

@property (nonatomic ,strong)LFBottomOneCell *oneCell;
@end

static NSString *cell = @"cell";
static NSString *GoodsCell = @"GoodsCell";
static NSString *nibCell = @"cnibCell";
static NSString *OneCell = @"OneCell";
static NSString *TwoCell = @"TwoCell";
static NSString *ThreeCell = @"ThreeCell";


@implementation LFOrderTableViewController

// 单例创建
+ (instancetype)allocWithZone:(struct _NSZone *)zone {
    
    static LFOrderTableViewController* stancetype;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        stancetype = [super allocWithZone:zone];
        
    [[NSNotificationCenter defaultCenter] addObserver: stancetype selector:@selector(loadModel:) name:@"model" object:nil];
    });
       [[NSNotificationCenter defaultCenter]addObserver:stancetype selector:@selector(clickAddButton:) name:@"papapa" object:nil];

    return stancetype;
}


// 视图将要显示
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    self.bgView.backgroundColor = [UIColor whiteColor];
    
    if (self.freshOrderArray.count || self.cellCount.count) {
        self.bgView.alpha = 0;
    }else {
        self.bgView.alpha = 1;
    }
    
//    self.bgView.alpha = self.freshOrderArray.count ? 0: 1;
//    
//    self.bgView.alpha = self.cellCount.count ? 0 : 1;
    
    
    self.bgFootView.alpha = self.cellCount.count ? 1 : 0;
    
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    
    
     [super viewDidLoad];

    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds style:UITableViewStyleGrouped];
    

    // 注册 cell 单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"LFGoodsCell" bundle:nil] forCellReuseIdentifier:GoodsCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LFTopTableViewCell" bundle:nil] forCellReuseIdentifier:nibCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LFBottomOneCell" bundle:nil] forCellReuseIdentifier:OneCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LFBottomTwoCell" bundle:nil] forCellReuseIdentifier:TwoCell];
    [self.tableView registerNib:[UINib nibWithNibName:@"LFBottomThreeCell" bundle:nil] forCellReuseIdentifier:ThreeCell];
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    // 预估行高
    self.tableView.estimatedRowHeight = 90;
    
    self.tableView. rowHeight = UITableViewAutomaticDimension;;

    #pragma mark 加减号按钮的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(disBtnClick:) name:@"Deletegoods" object:nil ];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addBtnClick:)  name:@"add" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(desBtnClick:)  name:@"des" object:nil];
    

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(desButton) name:@"desClick" object:nil];
    
    
    
    self.bgFootView.alpha = 1;

}

#pragma mark 按钮通知方法
// 减号按钮
- (void)disBtnClick:(NSNotification *)notifcation {
    
    UIAlertController* vc = [UIAlertController alertControllerWithTitle:@"是否要删除?" message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    // 创建action
    UIAlertAction* action1 = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction* _Nonnull action) {
      
        LFGoodsCell *goodsCell = notifcation.userInfo[@"cellKey"];

        NSIndexPath *path = [self.tableView indexPathForCell:goodsCell];

        NSMutableArray * tempM = [NSMutableArray arrayWithArray:self.cellCount];
        
        [tempM removeObjectAtIndex:path.row - 3];
        
        self.cellCount = tempM;
        
        [self.tableView reloadData];
    }];
    
    UIAlertAction* action2 = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleCancel handler:^(UIAlertAction* _Nonnull action) {
     
        LFGoodsCell *goodsCell = notifcation.userInfo[@"cellKey"];
        
        goodsCell.quantityLabel.text = @"1";
        goodsCell.hotSellerModel.ismix = 1;
    }];
       // 添加action
       [vc addAction:action1];
       [vc addAction:action2];
       // 显示
       [self presentViewController:vc animated:YES completion:nil];
}

// 加号
- (void) addBtnClick:(NSNotification *)notifcation {
    
    LFGoodsCell *goodsCell = notifcation.userInfo[@"cellKey"];
    
    self.addmoney += goodsCell.hotSellerModel.price.integerValue;
    
    self.certainView.money.text = [NSString stringWithFormat:@"%zd",self.addmoney];
    NSLog(@"%@",self.self.certainView.money.text);
}
// 减号
- (void) desBtnClick:(NSNotification *)notifcation {
    
    LFGoodsCell *goodsCell = notifcation.userInfo[@"cellKey"];
    
    self.addmoney -= goodsCell.hotSellerModel.price.integerValue;
    
    NSLog(@"%zd",self.addmoney);
    self.certainView.money.text = [NSString stringWithFormat:@"%zd",self.addmoney];

    
}
#pragma mark - 实现通知的方法
-(void)clickAddButton:(NSNotification *)sender{
    
    if (self.freshOrderArray == nil){
        self.freshOrderArray = [NSMutableArray array];
    }
    self.freshOrderModel  =  sender.userInfo[@"model"];
    self.bgFootView.alpha = 1;
    //是否包含当前模型
    BOOL isContain = NO;
    
    if (self.freshOrderArray.count == 0){
        [self.freshOrderArray addObject:self.freshOrderModel];
        isContain = YES;
    }else{
        
        for (LFFreshOrdergoodsModel *model in self.freshOrderArray){
            if([self.freshOrderModel.name isEqualToString:model.name] ){
                //说明包含模型
                isContain = YES;
            }
        }
    }
    
    if (isContain == NO){
        NSMutableArray *tempArray = [NSMutableArray array];
        for (int i = 0; i < self.freshOrderArray.count; i++)
        {
            [tempArray addObject:self.freshOrderArray[i]];
        }
        [tempArray addObject:self.freshOrderModel];
        
        self.freshOrderArray = tempArray.copy;
    }
    num++;
    self.tabBarItem.badgeValue = @(num).description;
    [self.tableView reloadData];
    
}
#pragma  mark  接受模型通知
- (void)loadModel:(NSNotification *)notifcation {
    if (self.cellCount == nil){
        self.cellCount = [NSMutableArray array];
    }
    self.model = notifcation.userInfo[@"modelkey"];
    self.bgFootView.alpha = 1;
    
    //是否包含当前模型
    BOOL isContain = NO;
    
    if (self.cellCount.count == 0){
        [self.cellCount addObject:self.model];
        isContain = YES;
    }else{
    
        for (LFHotSellerModel *model in self.cellCount){
                    if(self.model.id == model.id){
                        //说明包含模型
                        isContain = YES;
                    }
        }
    }

    if (isContain == NO){
        NSMutableArray *tempArray = [NSMutableArray array];
        for (int i = 0; i < self.cellCount.count; i++)
        {
            [tempArray addObject:self.cellCount[i]];
        }
        [tempArray addObject:self.model];
        self.cellCount = tempArray.copy;
    }
    
    num++;
    self.tabBarItem.badgeValue = @(num).description;
    
   [self.tableView reloadData];
    [self creatTimePickView];
}

- (void)desButton{
    
    num--;
    self.tabBarItem.badgeValue = @(num).description;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}


- (void)creatTimePickView {
    self.timePicker = [[KPTimePicker alloc] initWithFrame:self.view.bounds];
    self.timePicker.delegate = self;
    self.timePicker.lightColor = ThemeColor;
    self.timePicker.confirmColor = [UIColor colorWithRed:63.0 / 255 green:254.0 / 255 blue:250.0 / 255 alpha:1];
    self.timePicker.minimumDate = [NSDate date];
    self.timePicker.maximumDate = [[[self.timePicker.pickingDate dateByAddingMinutes:(60*24)] dateAtStartOfDay] dateBySubtractingMinutes:5];
}

-(void)show:(BOOL)show timePickerAnimated:(BOOL)animated{
    if(show){
        self.timePicker.pickingDate = [NSDate date];
        [self.view addSubview:self.timePicker];
    }
    else{
        [self.timePicker removeFromSuperview];
        self.navigationController.navigationBarHidden = NO;
        self.tabBarController.tabBar.hidden = NO;
    }
}

-(void)timePicker:(KPTimePicker *)timePicker selectedDate:(NSDate *)date{
    [self show:NO timePickerAnimated:YES];
    
    if(date){
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setLocale:[NSLocale currentLocale]];
        [dateFormatter setDateStyle:NSDateFormatterNoStyle];
        [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:1];
        LFBottomTwoCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        cell.timeLabel.text = [[dateFormatter stringFromDate:date] lowercaseString];
    }
}


#pragma mark -  数据源方法

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.freshOrderArray ? 3 : 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    if(section == 0){
          return 1;
    }else if (section == 1) {
        return   (self.cellCount.count ? 3 : 0 ) + self.cellCount.count;
    }else if (section == 2){
        return  (self.freshOrderArray.count ? 3 : 0 ) + self.freshOrderArray.count;
    }
    return 0;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0) {
        LFTopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nibCell forIndexPath:indexPath];
      
        
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
        
    }else {
        
        if (indexPath.row == 0) {
            LFBottomOneCell *cell = [tableView dequeueReusableCellWithIdentifier:OneCell forIndexPath:indexPath];
            self.oneCell = cell;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        }else if (indexPath.row == 1){
            
            LFBottomTwoCell *cell = [tableView dequeueReusableCellWithIdentifier:TwoCell forIndexPath:indexPath];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            return cell;
            
        }else if (indexPath.row == 2){
            
            LFBottomThreeCell *cell = [tableView dequeueReusableCellWithIdentifier:ThreeCell forIndexPath:indexPath];
  
            return cell;
        }
        
        //商品的cell
        LFGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:GoodsCell forIndexPath:indexPath];
    
      
        if (indexPath.section == 1) {
            
            cell.hotSellerModel = self.cellCount[indexPath.row - 3];
        }else {
            cell.freshOrderModel = self.freshOrderArray[indexPath.row - 3];
        }
        

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return cell;
    }
}

#pragma mark 确定按钮视图
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    
    if (section == 1 && self.bgView.alpha == 0) {

        LFcertainView *certainView = [[LFcertainView alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];
        self.bgFootView = certainView;
        
        certainView.backgroundColor = [UIColor whiteColor];
    
        certainView.delegate = self;
        
        for ( LFHotSellerModel *model  in self.cellCount) {
         
            NSInteger moeny  = model.price.integerValue * model.ismix;
            self.money += moeny;
            self.addmoney  += moeny;
        }
        
        certainView.money.text = [NSString stringWithFormat:@"%zd",self.money];
        
        self.money = 0;
        
        self.certainView = certainView;
        return certainView;
       
    }else if (section == 2) {
        
        
        LFcertainView *certainView = [[LFcertainView alloc] initWithFrame:CGRectMake(0, 0, 100, 80)];
        self.bgFootView = certainView;
        
        certainView.backgroundColor = [UIColor whiteColor];
        
        certainView.delegate = self;
        
        for ( LFFreshOrdergoodsModel *model  in self.freshOrderArray) {
            
            NSInteger moeny  = model.partner_price.integerValue * model.alreadyBuyCount;
            self.money += moeny;
            self.addmoney  += moeny;
        }
        
        certainView.money.text = [NSString stringWithFormat:@" 共  ￥%zd",self.money];
        
        self.money = 0;
        
        self.certainView = certainView;
        return certainView;
    }
    return nil;
}

#pragma mark cell点击事件方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 1 && indexPath.row == 2) {
        
        LFRemarkViewController *remarkVC = [LFRemarkViewController new];
        
        [self.navigationController pushViewController:remarkVC animated:YES];
        
    }else if (indexPath.section == 1 && indexPath.row == 1) {
        [self show:YES timePickerAnimated:YES];
        self.navigationController.navigationBarHidden = YES;
        self.tabBarController.tabBar.hidden = YES;
    
    }
    
}

#pragma mark 视图代理方法
- (void)certainView:(LFcertainView *)certainView {
    
    LFShopCarPayViewController *vc = [[LFShopCarPayViewController alloc] init];
    
    vc.cellArrayM = self.cellCount;
    
    vc.moeny = self.addmoney;
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark Footer高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    if (section == 1) {
        return 50;
    } else if (section == 2) {
        return 50;
    }
    return 5;
}

#pragma mark 组头和组尾的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 5;
}

-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];

}


#pragma mark - 懒加载
- (UIView *)bgView {
    if (!_bgView) {
        _bgView = [[UIView alloc] initWithFrame:self.view.bounds];
        UIButton * btn = [UIButton buttonLRWithImgName:nil title:@"去逛逛" color:[UIColor redColor] forSize:12 target:self action:@selector(gogogo) forControlEvents: UIControlEventTouchUpInside ];
        
        [btn setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateHighlighted];
        [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
        
        [_bgView addSubview:btn];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        
        imageView.image = [UIImage imageNamed:@"v2_shop_empty"];
        
        [_bgView addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
        
            make.centerX.equalTo(_bgView);
            make.top.offset(150);
            
        }];
        
        UILabel *goShopLabel = [[UILabel alloc] init];
    
        goShopLabel.textColor = [UIColor darkGrayColor];
        
        [goShopLabel setFont:[UIFont systemFontOfSize:13]];
        
        goShopLabel.text = @"亲,购物车空空的耶~赶紧去挑好吃的吧";
        
        [_bgView addSubview:goShopLabel];
        
        [goShopLabel mas_makeConstraints:^(MASConstraintMaker *make) {
           
            make.centerX.equalTo(_bgView);
            make.top.equalTo(imageView.mas_bottom).offset(20);
            
        }];
    
        [btn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_bgView);
            make.top.equalTo(goShopLabel.mas_bottom).offset(15);
            make.width.offset (100);
            make.height.offset (30);
        }];
        
        [self.view addSubview:_bgView];
    }
    return _bgView;
}
// 跳转到首页
- (void)gogogo {
    
    self.tabBarController.selectedIndex = 0;
    
//    [self.navigationController pushViewController:(UITabBarController *)self.view.window.rootViewController. animated:NO];
}

@end
